package cn.itcast.io.test;

import cn.itcast.io.a.file.filefilter.FileFilterBySuffix;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FilterFileByJava {

    private static final Object LINE_SEPARATOR = System.getProperty("line.separator");

    public static void main(String[] args) throws IOException {
        File sourceDir = new File("D:\\video\\SpringCloud\\SpringCloud_1\\codes\\microservicecloud\\microservicecloud-consumer-dept-80");
        File destDir = new File("tempFile\\javaFile.txt");
        FileFilterBySuffix fileFilter = new FileFilterBySuffix(".java");
        FileOutputStream fos = new FileOutputStream(destDir);
        //getFile(sourceDir, destDir, fileFilter, fos);
        fos.close();

        List<File> fileList = new ArrayList<>();
        getFile(sourceDir, fileFilter, fileList);
        System.out.println(fileList.size());
        write2File(fileList, destDir);

    }


    private static void getFile(File source, File dest, FileFilter fileFilter, OutputStream fos) throws IOException {
        File[] files = source.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                getFile(file, dest, fileFilter, fos);
            } else {
                if (fileFilter.accept(file)) {
                    String tempName = file.getAbsolutePath() + LINE_SEPARATOR;
                    fos.write(tempName.getBytes());
                    fos.flush();
                }
            }
        }
    }


    private static void getFile(File dir, FileFilter fileFilter, List<File> fileList) {
        if (dir != null) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    getFile(file, fileFilter, fileList);
                } else {
                    if (fileFilter.accept(file)) {
                        fileList.add(file);
                    }
                }
            }
        }
    }

    private static void write2File(List<File> fileList, File destDir) throws IOException {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(destDir);
            bos = new BufferedOutputStream(fos);
            for (File file : fileList) {
                String fileInfo = file.getAbsolutePath() + LINE_SEPARATOR;
                bos.write(fileInfo.getBytes());
            }
        } finally {
            if(bos != null){
                try{
                    bos.close();
                }catch (IOException e){
                    throw new RuntimeException("关闭失败！");
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭失败！");
                }
            }
        }
    }

}
